import React, { useEffect, useRef, useState,forwardRef, useImperativeHandle}  from "react";
import { withRouter } from "react-router-dom";
import './index.scss'
import commonConfig from 'static/js/commonConfig'
import { connect } from 'react-redux'
import {queryByBookIdInten,editBookStatus,setRemark,queryByBookId,getWordList,saveNewBook} from 'api/index'
import {notification, Button, Modal,Tabs,Form,Select,Cascader,Spin,Alert, message} from 'antd'
import {checkDraftData} from 'redux/action'
import LlxForm from 'components/LlxForm'
import  UploadPicture  from 'components/Upload/index'
// 查看更多弹框
import LookMore from 'components/Operations/LookMore'
import LlxHead from "components/Operations/LlxHead";

import BookContent from "./BookContent";

const {Option} = Select
const { TabPane } = Tabs;
const { SHOW_CHILD } = Cascader;
const {getPageJurisdiction,getStatusJurisdiction,statusValue} = commonConfig

// 泛读详情
const BookMain = forwardRef((props, ref) => {
  const {form,dictionaries,disabled,userName} = props

  const BookContentRef = useRef() //单词数据

  //选择数据
  const [dataSource,setDataSource] = useState(form.getFieldValue().content?form.getFieldValue().content.map((i,index)=>{
    return {
      id:i.id||'',
      sort:i.sort || index + 1,
      audioUrl:i.audioUrl,
      pictureUrl:i.pictureUrl,
      captionUrl:i.captionUrl,
      content:i.content,
      key:index + 1 +''
    }
  }):[])

  useImperativeHandle(ref, () => ({
    BookContent:dataSource
  }));

  const [wordOptions,setWordOptions] = useState([])

  const options = wordOptions.map(d => <Option value={d.wordName} key={d.id}>{d.wordName}</Option>);

  const handleSearch = async value => {
    const res = await getWordList({currPage:1,pageSize:20,wordName:value})
    setWordOptions(res.result.records)
  };

  const newItem = [
    {label: '名称',type:'input', name: 'bookName',rules:[
      {
        required: true,
        message: '请输入绘本名称'
      },
    ], span: 8 },
    {label: '标签', name: 'label' , span: 8,render: () => {
    return <Cascader disabled={disabled}  maxTagCount="responsive" showCheckedStrategy={SHOW_CHILD} fieldNames={{value:'id',label:'labelName'}} options={dictionaries.Label} multiple placeholder="请选择标签" />
     } },
     {label: '适合年纪', name: 'ageId' , span: 8,render: () => {
     return <Select
     disabled={disabled}
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择适合年纪'}
     options={dictionaries.AgeRange}
   >
   </Select>
     } },
    {label: '主题', name: 'theme' , span: 8,render: () => {
      return <Select
      disabled={disabled}
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择主题'}
      mode="multiple"
      options={dictionaries.Theme}
    >
    </Select>
    } },
    {label: '出版社', name: 'publisher' , span: 8,render: () => {
    return <Select
    disabled={disabled}  
    allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'dictValue',label:'dictValue'}}
      placeholder={'请选择类型'}
      options={dictionaries.Publisher}
    >
    </Select>
     } },
    {label: '配音', name: 'dub', span: 8 ,render:()=>{
     return <Select
     disabled={disabled}
     allowClear
     optionFilterProp="dictValue"
     showSearch
     maxTagCount={1}
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择配音'}
     options={dictionaries.isDub}
   >
   </Select>
    }},
    {label: '字幕类型', name: 'captionPositionId', span: 8 ,rules:[
      {
        required: true,
        message: '请选择字幕类型'
      },
    ],render:()=>{
     return <Select
     disabled={disabled}
     allowClear
     optionFilterProp="dictValue"
     showSearch
     maxTagCount={1}
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择字幕类型'}
     options={dictionaries.CaptionPosition}
   >
   </Select>
    }},
    {label: '类型', name: 'bookTypeId' , span: 8,render: () => {
      return <Select
     disabled={disabled}
      allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择类型'}
     options={dictionaries.BookType}
   >
   </Select>
    } },
    {label: '分享', name: 'share' , span: 8,render: () => {
     return <Select
     disabled={disabled}
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择系列'}
     options={dictionaries.shareOption}
   >
   </Select>
    } },
    {label: '系列', name: 'serialId' , span: 8,render: () => {
     return <Select
     disabled={disabled}
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择系列'}
     options={dictionaries.SeriesName}
   >
   </Select>
    } },
    {label: '蓝思值',type:'input', name: 'lexile' , span: 8},
    {label: '级别', name: 'levelId' , span: 8,render: () => {
     return <Select
     disabled={disabled}
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择级别'}
     options={dictionaries.Level}
   >
   </Select>
    } },
    {label: '核心单词', name: 'coreWord' , span: 8,render: (text,row) => {
     return <Select
     placeholder={'请输入搜索单词'}
     defaultActiveFirstOption={false}
     showArrow={false}
     disabled={disabled}
     filterOption={false}
     mode="multiple"
     onSearch={handleSearch}
     notFoundContent={null}
   >
     {options}
   </Select>
    } },
    {label: '阅读模式', name: 'readModeId' , span: 8,render: () => {
     return <Select
     disabled={disabled}
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择时长'}
     options={dictionaries.ReadMode}
   >
   </Select>
    } },
    {label: '开页方式', name: 'pageId' , span: 8,render: () => {
     return <Select
     disabled={disabled}
     allowClear
     optionFilterProp="dictValue"
     showSearch
     fieldNames={{value:'id',label:'dictValue'}}
     placeholder={'请选择开页方式'}
     options={dictionaries.PageType}
   >
   </Select>
    } },
    {label: '泛读简介',type:'textArea', name: 'remark', span: 8 },
    {label: '书籍封面', name: 'pictureUrl', span: 8,rules:[
      {
        required: true,
        message: '请上传视频封面'
      },
    ],render:()=>{
      return  <UploadPicture disabled={disabled} pictureUrl={form.getFieldValue().pictureUrl} setPhoto={(value)=>form.setFieldsValue({...form.getFieldValue(),pictureUrl:value})}></UploadPicture>
    }},
]
  
  // 获取修改的数据

  return <div  className='info-main'>
    <Tabs defaultActiveKey="1" tabPosition={'left'}>
    <TabPane tab="基本信息" key="1">
     <LlxForm  disabled={disabled} form={form} labelCol={5} formItem={newItem} />
    </TabPane>
    <TabPane tab="绘本内容" key="2">
      <BookContent id={form.getFieldValue().id} setDataSource={setDataSource} dataSource={dataSource} ref={BookContentRef} disabled={disabled} dictionaries={dictionaries} form={form} userName={userName}></BookContent>
    </TabPane>
  </Tabs>

  </div>
})
// 保存数据
const DataDialog  = (props) => {
  const {isModalVisible, setIsModalVisible,form,changeStatus,UserSpecies,userName,disabled,QandPQ,dataSource} = props
  const value = statusValue(changeStatus,form.getFieldValue().bookStatus) //修改的状态

  const loading = useRef(false)

  const manager = value==='Q'||value==='PQ'?QandPQ:UserSpecies

  const [formItem] = Form.useForm();//泛读详情

  const item = ['N','PN','P'].includes(value)?[
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
  ]:[
    {label: '负责人', name: 'manager' , span: 24 ,rules:[
      {
        required: true,
        message: '请选择负责人'
      },
    ],render:()=>{
      return  <Select
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'userName',label:'userName'}}
      placeholder={'请选择负责人'}
      options={manager}
    >
    </Select>
    }},
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
  ]
  
 const handleCancel = () => {
    setIsModalVisible(false);
 };
 
 const handleOk = () => {
   if(loading.current) {
    message.error('请勿多次点击')
   }

  loading.current=true
  formItem.validateFields().then(async()=>{
  //  1更改状态
  await editBookStatus({
    id: form.getFieldValue().id,
    bookStatus: value,
    qmanager: value==='Q'||value==='PQ'?formItem.getFieldValue().manager:'',
    rmanager: value==='R'||value==='PR'?formItem.getFieldValue().manager:'',
  })
   
  // 留言
  await setRemark({
    manager: formItem.getFieldValue().manager||'',
    dataId: form.getFieldValue().id,
    type: 'BOOK',
    remark: formItem.getFieldValue().remark,
    statusNow: form.getFieldValue().bookStatus,
    statusNext: value
  })

  //  2修改数据
   if(!disabled){
          const data = form.getFieldValue()
          data.labels = data.label?data.label.map(i=>{
            return {id:i[1]}
            }):[]
          data.themes = data.theme?data.theme.map(i=>{
            return {id:i}
            }):[]
           
          data.coreWords = data.coreWord?data.coreWord.join(' '):''
    
          data.bkBookContentFlows=dataSource?dataSource.filter(i=>i.pictureUrl).map((i,j)=>{
            return {
              sort:j+1,
              audioUrl:i.audioUrl,
              pictureUrl:i.pictureUrl,
              content:i.content,
              captionUrl:i.captionUrl
            }
          }):form.getFieldValue().contentFlows

          delete data.bookStatus
          delete data.rmanager
          delete data.qmanager
          delete data.updateTime
          delete data.content
          delete data.contentFlows
          delete data.updateBy
          delete data.updateTime
          delete data.theme
          delete data.label
    
          const res = await saveNewBook(data)
    
    
          if(res.result){
            const key = `open${Date.now()}`;
    
    
            const value = res.result.replace(/空/g, '空<br/>').split('<br/>').map((i,index)=>{
              return <div key={index}>
                {i}
              </div>
            })
      
            notification.open({
              message: '字幕时间为空',
              description:value,
              btn:<Button type="primary" size="small" onClick={() => notification.close(key)}>
              确定
            </Button>,
              key
            });
          }
    
          setIsModalVisible(false)
         
        notification.success({
          message: '保存成功',
          description: '操作人：' + userName,
          duration:1.5
        });
      
        props.getBookInfoFn()
        formItem.resetFields()
        setIsModalVisible(false);
   } else {
    notification.success({
      message: '状态变更成功',
      description: '操作人：' + userName,
      duration:1.5
    });

    props.getBookInfoFn()
    formItem.resetFields()
    setIsModalVisible(false);
   }
  })
  loading.current=false
 }

return   <>
<Modal onOk={handleOk}  width={600} title="保存数据" visible={isModalVisible}  onCancel={handleCancel}>
      <Alert className="edit-alert" message={'你确定要修改状态至' + value + '吗？'} type="success" />

     <LlxForm form={formItem} labelCol={3} formItem={item} />
 </Modal>
</>
}


function BookInfo(props) {

  const {examineStatus} = props
  const [isModalVisibleMore,setIsModalVisibleMore] = useState(false)
  const [isModalVisibleData,setIsModalVisibleData] = useState(false)
  const [disabled,setDisabled] = useState(false)
  const [loading,setLoading] = useState(true)
  const id = commonConfig.getUrlParams(props).id
  const [form] = Form.useForm();//泛读详情
  const head = useRef()
  const main = useRef()
  const [preservationJurisdiction,setPreservationJurisdiction] = useState({})
  // 1.获取数据
  useEffect(()=>{
    getBookInfoFn()
  }, [examineStatus])// eslint-disable-line react-hooks/exhaustive-deps


  // 2.查看更多
  const getMore = () => {
    setIsModalVisibleMore(true)
  }
  // 3.保存数据
  const preservationData = () => {
    console.log(main.current);
   const value = statusValue(head.current.current,form.getFieldValue().bookStatus)
   if(!getStatusJurisdiction(preservationJurisdiction[0],preservationJurisdiction[1],preservationJurisdiction[2],preservationJurisdiction[3],preservationJurisdiction[4],preservationJurisdiction[5]).includes(value)) {
    notification.error({
      message: '该数据你无法保存，请联系管理员',
      description: '操作人：' + props.userInfo.user.userName,
      duration:2
    });
    return
   }
  
  // 打开弹框 输入备注 修改状态 修改数据
  setIsModalVisibleData(true)


  }
  // 4.更新数据
  const getBookInfoFn = async () => {
    if(examineStatus){
      const res = await queryByBookIdInten(id)
      if(!res.result.id){
        notification.error({
          message: '该泛读未发布过',
          duration:1.5
        });
        props.checkDraftDataBtn()
        setLoading(false)
        return
      }
      form.setFieldsValue(res.result)
      form.setFieldsValue({
        content:res.result.contents||[],
        coreWord:res.result.coreWords?res.result.coreWords.split(' ')||[res.result.coreWords]:[],
        wordList:res.result.bookWords,
        label:res.result.labels?.map(i=>{
          return [i.labelCategoryId,i.id]
          }),
        theme:res.result.themes?.map(i=>i.id)
      })
      setDisabled(true)
  
      setLoading(false)
    } else {
      const res = await queryByBookId(id)
      form.setFieldsValue(res.result)
      form.setFieldsValue({
        content:res.result.contentFlows||[],
        coreWord:res.result.coreWords?res.result.coreWords.split(' ')||[res.result.coreWords]:[],
        wordList:res.result.bookWordFlows,
        label:res.result.labels?.map(i=>{
          return [i.labelCategoryId,i.id]
          }),
        theme:res.result.themes?.map(i=>i.id)
      })
      setDisabled(!getPageJurisdiction(res.result.bookStatus,res.result.createBy,props.userInfo.user.userName))

      setPreservationJurisdiction([res.result.bookStatus,res.result.createBy,res.result.rmanager,res.result.qmanager,props.userInfo.user.userName,props.userInfo.roles.map(i => i.id).includes(7)])
     
      setLoading(false)
    }
  }

  return <div className="app-content-info animate__animated animate__fadeIn">
  {
    !loading?(
      <>
      <LlxHead nameType={'bookName'} statusType={'bookStatus'} examineStatus={examineStatus}  ref={head} preservationJurisdiction={preservationJurisdiction}  preservationData={preservationData} userName={props.userInfo.user.userName} role={props.userInfo.roles.map(i => i.id).includes(7)} form={form} getMore={getMore}></LlxHead>
       
       {/* 查看更多信息 */}
       <LookMore  type={'BOOK'} preservationJurisdiction={preservationJurisdiction}  isModalVisible={isModalVisibleMore}  setIsModalVisible={setIsModalVisibleMore} ></LookMore>
       {/* 保存数据 */}
       <DataDialog dataSource={main.current?.BookContent} getBookInfoFn={getBookInfoFn} disabled={disabled} form={form} QandPQ={props.dictionaries.QandPQ} UserSpecies={props.dictionaries.UserSpecies} userName={props.userInfo.user.userName} status={form} changeStatus={head.current?.current}   id={id} isModalVisible={isModalVisibleData} setIsModalVisible={setIsModalVisibleData} ></DataDialog>
       
       {/* 主要内容区域 */}
       {/* 1.草稿可编辑 */}
       <BookMain ref={main} form={form} userName={props.userInfo.user.userName} dictionaries={props.dictionaries} disabled={disabled}></BookMain>
      </>
    ):<Spin className="info-loading" tip="Loading..."></Spin>
  }
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    checkDraftDataBtn: () => dispatch(checkDraftData())
  }
}

export default connect((state)=>{
  return {examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(withRouter(BookInfo))